import router from './router'
import {asyncRouterMap,constantRouterMap} from './router'
import {getToken,getRoles} from './utils/auth'
import store from './store'

const whiteList = ['/login']// no redirect whitelist

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
      return roles.some(role => route.meta.roles == role.code );
    } else {
      return false
    }
  }

  /**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(routes, roles) {
    const res = []
    routes.forEach(route => {
      const tmp = { ...route }
      if (hasPermission(roles, tmp)) {
        // if (tmp.children) {
        //   tmp.children = filterAsyncRouter(tmp.children, roles)
        // }
        res.push(tmp)
      }
    })
    return res
  }
router.beforeEach((to, from, next) => {
    if(getToken()) {
        if (to.path === '/login') {
            next({ path: '/setting/account' })
        }else {
            if(store.state.roleList.length === 0){
                let addRouters = filterAsyncRouter(asyncRouterMap,JSON.parse(getRoles()))
                addRouters = constantRouterMap.concat(addRouters)

                router.options.routes = addRouters;
                router.addRoutes(addRouters)
                store.commit('SAVE_list',addRouters)
                next({ ...to, replace: true })
            }else{
                next()
            }
        }
       
    }else {
        if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
            next()
          } else {
           
            next({ path: '/login' }) // 否则全部重定向到登录页
           
          }
    }
})